import sys
import os
import json
from PySide6.QtWidgets import (QApplication, QMainWindow, QPushButton, QLabel, QFileDialog,
                               QVBoxLayout, QWidget, QTableWidget, QTableWidgetItem, 
                               QHeaderView, QHBoxLayout, QFrame, QTextEdit, QLineEdit,
                               QGroupBox, QFormLayout, QMessageBox, QSplitter)
from PySide6.QtGui import QPixmap, QImage, QFont
from PySide6.QtCore import Qt

class ConfigTool(QMainWindow):
    def __init__(self):
        super().__init__()
        # 数据存储
        self.main_images = []    # 主图数据：[路径1, 路径2, ...]
        self.detail_images = []  # 详情图数据：[路径1, 路径2, ...]
        self.sku_data = []       # SKU图数据：[[路径, 价格, 编码], ...]
        self.current_img_type = ""  # 当前图片类型
        self.init_main_window()
        
    def init_main_window(self):
        """初始化主窗口"""
        self.setWindowTitle("配置文件工具（SKU布局优化版）")
        self.setGeometry(100, 100, 800, 600)
        
        # 主布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        
        # 1. 说明文本
        info_label = QLabel("选择图片后会自动更新配置信息（字典格式）")
        info_label.setAlignment(Qt.AlignCenter)
        info_label.setStyleSheet("font-size: 14px; margin: 10px 0;")
        main_layout.addWidget(info_label)
        
        # 2. 按钮布局
        btn_layout = QHBoxLayout()
        btn_layout.setSpacing(20)
        btn_layout.setContentsMargins(20, 0, 20, 0)
        
        # 选择主图按钮
        self.main_btn = QPushButton("选择主图")
        self.main_btn.setStyleSheet("padding: 8px 16px; font-size: 14px;")
        self.main_btn.clicked.connect(lambda: self.select_images("main"))
        btn_layout.addWidget(self.main_btn)
        
        # 选择详情图按钮
        self.detail_btn = QPushButton("选择详情图")
        self.detail_btn.setStyleSheet("padding: 8px 16px; font-size: 14px;")
        self.detail_btn.clicked.connect(lambda: self.select_images("detail"))
        btn_layout.addWidget(self.detail_btn)
        
        # 选择SKU图按钮
        self.sku_btn = QPushButton("选择SKU图")
        self.sku_btn.setStyleSheet("padding: 8px 16px; font-size: 14px;")
        self.sku_btn.clicked.connect(lambda: self.select_images("sku"))
        btn_layout.addWidget(self.sku_btn)
        
        main_layout.addLayout(btn_layout)
        
        # 3. 配置预览文本框
        text_frame = QFrame()
        text_frame.setFrameShape(QFrame.StyledPanel)
        text_frame.setStyleSheet("margin: 10px 20px; padding: 10px;")
        text_layout = QVBoxLayout(text_frame)
        
        text_label = QLabel("配置信息预览（自动更新）：")
        text_label.setStyleSheet("font-weight: bold; margin-bottom: 5px;")
        text_layout.addWidget(text_label)
        
        self.config_text = QTextEdit()
        self.config_text.setReadOnly(True)
        self.config_text.setFont(QFont("Consolas", 10))
        self.config_text.setStyleSheet("background-color: #f5f5f5;")
        text_layout.addWidget(self.config_text)
        
        main_layout.addWidget(text_frame)
        
        # 4. 状态区域
        self.status_frame = QFrame()
        self.status_frame.setFrameShape(QFrame.StyledPanel)
        self.status_frame.setStyleSheet("margin: 10px 20px; padding: 10px;")
        status_layout = QVBoxLayout(self.status_frame)
        
        self.main_status = QLabel("主图：未选择任何文件")
        self.detail_status = QLabel("详情图：未选择任何文件")
        self.sku_status = QLabel("SKU图：未选择任何文件")
        self.main_status.setStyleSheet("color: gray;")
        self.detail_status.setStyleSheet("color: gray;")
        self.sku_status.setStyleSheet("color: gray;")
        
        status_layout.addWidget(self.main_status)
        status_layout.addWidget(self.detail_status)
        status_layout.addWidget(self.sku_status)
        
        main_layout.addWidget(self.status_frame)
        
        main_layout.addStretch()
        
        # 初始更新配置文本
        self.update_config_text()
        
    def select_images(self, img_type):
        """选择图片，初始化对应类型数据并更新配置"""
        type_info = {
            "main": {"title": "主图", "data": self.main_images, "status": self.main_status, 
                    "color": "green", "col_count": 3},
            "detail": {"title": "详情图", "data": self.detail_images, "status": self.detail_status, 
                      "color": "blue", "col_count": 3},
            "sku": {"title": "SKU图", "data": self.sku_data, "status": self.sku_status, 
                   "color": "purple", "col_count": 5}
        }
        
        file_types = "图片文件 (*.jpg *.jpeg *.png *.bmp *.gif);;所有文件 (*.*)"
        files, _ = QFileDialog.getOpenFileNames(self, f"选择{type_info[img_type]['title']}文件", os.getcwd(), file_types)
        
        if files:
            # 初始化数据
            if img_type == "main":
                self.main_images = files
                display_data = self.main_images
            elif img_type == "detail":
                self.detail_images = files
                display_data = self.detail_images
            else:
                self.sku_data = [[path, "", ""] for path in files]
                display_data = self.sku_data
            
            # 更新状态
            type_info[img_type]["status"].setText(f"{type_info[img_type]['title']}：已选择 {len(files)} 个文件")
            type_info[img_type]["status"].setStyleSheet(f"color: {type_info[img_type]['color']};")
            
            # 显示表格
            self.current_img_type = img_type
            self.show_image_table(type_info[img_type]["title"], display_data)
            
            # 更新配置文本框
            self.update_config_text()
    
    def show_image_table(self, title, display_data):
        """创建图片表格（SKU图采用水平布局过滤区）"""
        # 新窗口
        self.result_window = QMainWindow()
        self.result_window.setWindowTitle(f"{title}列表")
        self.result_window.setGeometry(200, 200, 1200 if self.current_img_type == "sku" else 1000, 600)
        
        # 主部件与布局
        central_widget = QWidget()
        self.result_window.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        
        # 标题
        title_text = f"{title} - 共 {len(display_data)} 个文件"
        if self.current_img_type == "sku":
            title_text += " | 支持批量选择和批量设置"
        title_label = QLabel(title_text)
        title_label.setStyleSheet("font-size: 16px; font-weight: bold; margin: 10px 0;")
        main_layout.addWidget(title_label)
        
        # SKU图特殊功能区（水平布局）
        if self.current_img_type == "sku":
            # 功能区容器（水平布局）
            function_frame = QFrame()
            function_frame.setFrameShape(QFrame.StyledPanel)
            function_frame.setStyleSheet("padding: 10px; margin-bottom: 10px;")
            function_layout = QHBoxLayout(function_frame)
            function_layout.setSpacing(20)  # 各功能块之间的间距
            
            # 1. 搜索过滤区（水平放置）
            search_frame = QFrame()
            search_layout = QHBoxLayout(search_frame)
            search_layout.setContentsMargins(0, 0, 0, 0)
            
            search_label = QLabel("搜索文件名：")
            self.search_input = QLineEdit()
            self.search_input.setPlaceholderText("输入关键词过滤（如：加绒）")
            self.search_input.setMinimumWidth(200)
            self.search_input.textChanged.connect(self.filter_sku_items)
            
            search_layout.addWidget(search_label)
            search_layout.addWidget(self.search_input)
            function_layout.addWidget(search_frame)
            
            # 添加分隔线
            line = QFrame()
            line.setFrameShape(QFrame.VLine)
            line.setFrameShadow(QFrame.Sunken)
            function_layout.addWidget(line)
            
            # 2. 批量设置区（水平放置）
            batch_frame = QFrame()
            batch_layout = QHBoxLayout(batch_frame)
            batch_layout.setContentsMargins(0, 0, 0, 0)
            batch_layout.setSpacing(10)
            
            # 价格设置
            price_label = QLabel("批量设置价格：")
            self.batch_price = QLineEdit()
            self.batch_price.setMaximumWidth(100)
            batch_price_btn = QPushButton("应用")
            batch_price_btn.clicked.connect(lambda: self.batch_update("price"))
            
            # 编码设置
            code_label = QLabel("批量设置编码：")
            self.batch_code = QLineEdit()
            self.batch_code.setMaximumWidth(150)
            batch_code_btn = QPushButton("应用")
            batch_code_btn.clicked.connect(lambda: self.batch_update("code"))
            
            # 添加到布局
            batch_layout.addWidget(price_label)
            batch_layout.addWidget(self.batch_price)
            batch_layout.addWidget(batch_price_btn)
            batch_layout.addSpacing(20)  # 价格和编码区域之间的间距
            batch_layout.addWidget(code_label)
            batch_layout.addWidget(self.batch_code)
            batch_layout.addWidget(batch_code_btn)
            
            function_layout.addWidget(batch_frame)
            
            # 填充剩余空间
            function_layout.addStretch()
            
            # 添加功能区到主布局
            main_layout.addWidget(function_frame)
        
        # 创建表格
        self.table = QTableWidget(len(display_data), 
                                 5 if self.current_img_type == "sku" else 3)
        
        # 表格设置（SKU图支持批量选择）
        if self.current_img_type == "sku":
            self.table.setSelectionMode(QTableWidget.ExtendedSelection)  # 支持Ctrl/Shift批量选择
            self.table.setSelectionBehavior(QTableWidget.SelectRows)     # 整行选择
            self.table.setDragDropMode(QTableWidget.NoDragDrop)          # 取消拖拽
            self.table.itemChanged.connect(self.on_sku_item_changed)     # 监听单元格变化
        
        # 表头设置
        if self.current_img_type == "sku":
            self.table.setHorizontalHeaderLabels(["缩略图", "序号", "文件路径", "价格", "商家编码"])
            # 列宽设置
            self.table.setColumnWidth(0, 80)
            self.table.setColumnWidth(1, 60)
            self.table.setColumnWidth(3, 100)
            self.table.setColumnWidth(4, 150)
        else:
            self.table.setHorizontalHeaderLabels(["缩略图", "序号", "文件路径"])
            # 列宽设置
            self.table.setColumnWidth(0, 80)
            self.table.setColumnWidth(1, 60)
        # 路径列自动拉伸
        self.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
        # 行高
        self.table.verticalHeader().setDefaultSectionSize(60)
        
        # 填充表格内容
        self.fill_table_data(display_data)
        
        main_layout.addWidget(self.table)
        
        # 关闭按钮
        close_btn = QPushButton("关闭")
        close_btn.clicked.connect(self.result_window.close)
        close_btn.setStyleSheet("padding: 8px; margin: 10px;")
        main_layout.addWidget(close_btn, alignment=Qt.AlignCenter)
        
        self.result_window.show()
    
    def fill_table_data(self, display_data, filtered_rows=None):
        """填充表格数据，支持过滤显示"""
        # 清空表格
        self.table.clearContents()
        self.table.setRowCount(len(display_data))
        
        # 记录所有行的可见状态（用于过滤）
        self.visible_rows = []
        
        for row in range(len(display_data)):
            # 如果有过滤条件且当前行不在过滤结果中，则跳过
            if filtered_rows is not None and row not in filtered_rows:
                self.table.setRowHidden(row, True)
                continue
            
            self.table.setRowHidden(row, False)
            self.visible_rows.append(row)
            
            # 1. 缩略图列
            thumb_widget = QWidget()
            thumb_layout = QHBoxLayout(thumb_widget)
            thumb_layout.setContentsMargins(5, 5, 5, 5)
            
            # 获取图片路径
            file_path = display_data[row][0] if self.current_img_type == "sku" else display_data[row]
            
            try:
                image = QImage(file_path)
                if not image.isNull():
                    scaled_img = image.scaled(50, 50, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                    pixmap = QPixmap.fromImage(scaled_img)
                    thumb_label = QLabel()
                    thumb_label.setPixmap(pixmap)
                else:
                    thumb_label = QLabel("无法预览")
            except:
                thumb_label = QLabel("无法预览")
            thumb_layout.addWidget(thumb_label, alignment=Qt.AlignCenter)
            self.table.setCellWidget(row, 0, thumb_widget)
            
            # 2. 序号列（显示原始序号，不受过滤影响）
            index_item = QTableWidgetItem(str(row + 1))
            index_item.setTextAlignment(Qt.AlignCenter)
            index_item.setFlags(Qt.ItemIsEnabled)  # 不可编辑
            self.table.setItem(row, 1, index_item)
            
            # 3. 路径列
            path_item = QTableWidgetItem(file_path)
            path_item.setToolTip(file_path)
            path_item.setFlags(Qt.ItemIsEnabled)  # 不可编辑
            self.table.setItem(row, 2, path_item)
            
            # 4. SKU专属列
            if self.current_img_type == "sku":
                # 价格列
                price_item = QTableWidgetItem(display_data[row][1])
                price_item.setTextAlignment(Qt.AlignCenter)
                self.table.setItem(row, 3, price_item)
                
                # 商家编码列
                code_item = QTableWidgetItem(display_data[row][2])
                code_item.setTextAlignment(Qt.AlignCenter)
                self.table.setItem(row, 4, code_item)
    
    def filter_sku_items(self):
        """根据搜索框内容过滤SKU项（匹配文件名）"""
        if self.current_img_type != "sku":
            return
            
        keyword = self.search_input.text().lower()
        if not keyword:
            # 无关键词时显示所有项
            self.fill_table_data(self.sku_data)
            return
        
        # 筛选包含关键词的行（匹配文件名）
        filtered_rows = []
        for row, sku in enumerate(self.sku_data):
            file_name = os.path.basename(sku[0]).lower()
            if keyword in file_name:
                filtered_rows.append(row)
        
        # 刷新表格只显示筛选结果
        self.fill_table_data(self.sku_data, filtered_rows)
        QMessageBox.information(self.result_window, "筛选结果", 
                              f"找到 {len(filtered_rows)} 个包含 '{keyword}' 的文件")
    
    def batch_update(self, field):
        """批量更新选中项的价格或商家编码"""
        if self.current_img_type != "sku":
            return
            
        # 获取选中的行
        selected_rows = set()
        for item in self.table.selectedItems():
            selected_rows.add(item.row())
        
        if not selected_rows:
            QMessageBox.warning(self.result_window, "提示", "请先选择要更新的项（可按住Ctrl/Shift批量选择）")
            return
        
        # 获取要更新的值
        if field == "price":
            value = self.batch_price.text()
            col = 3  # 表格中的价格列索引
            data_col = 1  # sku_data中的价格索引
        else:
            value = self.batch_code.text()
            col = 4  # 表格中的编码列索引
            data_col = 2  # sku_data中的编码索引
        
        # 更新数据
        for row in selected_rows:
            # 只更新可见行
            if row in self.visible_rows:
                self.sku_data[row][data_col] = value
                self.table.item(row, col).setText(value)
        
        # 更新配置文本
        self.update_config_text()
        QMessageBox.information(self.result_window, "更新成功", 
                              f"已为 {len(selected_rows)} 个选中项更新{field}")
    
    def on_sku_item_changed(self, item):
        """监听SKU表格的单元格变化"""
        # 只处理价格列（3）和编码列（4）的变化
        if self.current_img_type == "sku" and item.column() in [3, 4]:
            row = item.row()
            col = item.column() - 2  # 转换为sku_data中的索引（1:价格，2:编码）
            self.update_sku_data(row, col, item.text())
    
    def update_sku_data(self, row, col, value):
        """更新SKU图的价格或编码数据，并刷新配置文本"""
        if 0 <= row < len(self.sku_data) and 1 <= col <= 2:
            self.sku_data[row][col] = value
            self.update_config_text()
        
    def update_data_after_sort(self, from_row, to_row):
        """排序后更新原始数据（主图/详情图）"""
        if self.current_img_type == "main":
            self.main_images[from_row], self.main_images[to_row] = self.main_images[to_row], self.main_images[from_row]
            self.fill_table_data(self.main_images)
        elif self.current_img_type == "detail":
            self.detail_images[from_row], self.detail_images[to_row] = self.detail_images[to_row], self.detail_images[from_row]
            self.fill_table_data(self.detail_images)
        
        self.update_config_text()
    
    def update_config_text(self):
        """将所有数据整理为字典，更新到文本编辑框"""
        config_dict = {
            "main_images": self.main_images,
            "detail_images": self.detail_images,
            "sku_images": []
        }
        
        # 处理SKU数据
        for sku in self.sku_data:
            config_dict["sku_images"].append({
                "path": sku[0],
                "price": sku[1],
                "code": sku[2]
            })
        
        # 转换为格式化的JSON字符串
        config_str = json.dumps(config_dict, ensure_ascii=False, indent=4)
        self.config_text.setText(config_str)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ConfigTool()
    window.show()
    sys.exit(app.exec())